<?php
/*
 * MiniMe - a minimalistic OStatus complient microblogging tool
 * Copyright (C) 2010, Tuomas Koski - koski.tuomas@gmail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @author     Tuomas Koski <koski.tuomas@gmail.com>
 * @copyright  Tuomas Koski
 * @license    http://www.gnu.org/licenses/lgpl.txt
 */
class Controller_Pubsubhubbub_Callback extends Controller_Abstract implements Controller_Interface {
    
    /**
     * 
     * @var Minime_Pubsubhubbub_Subscription
     */
    private  $subscription;
    
    public function __construct($getParams, $postParams, $phpInput, $conf) {

        parent::__construct($getParams, $postParams, $phpInput, $conf);
        
    }
    
    public function execute() {
        
        file_put_contents  ("/tmp/minime-callback.input", print_r(apache_request_headers(), true) . "\n\n" . $this->phpInput . "\n\n" . print_r($_GET, true) . "\n\n" . print_r($_POST, true));
        
        if(!$this->findAndLoadPubsubhubbubSubscription()) {
            $this->output = "Pubsubhubbub Subscription not found.";
            $this->headers[404] = "HTTP/1.0 404 Not Found";
            return;
        }
        if($this->getChallenge() !== null) {
            // This means we have a channenge.
            // TODO, check that the subscriptions match
            
            $this->output = $this->getChallenge();
        } else {
            $this->headers['X-Hub-On-Behalf-Of'] = $this->subscription->getAmountOfSubscribers();
            if( isset($_SERVER['HTTP_X_HUB_SIGNATURE']) ) {
                parse_str($_SERVER['HTTP_X_HUB_SIGNATURE'], $result);
                if (isset($result['sha1']) && $result['sha1'] == hash_hmac('sha1', $this->phpInput, $this->subscription->getSecret())) {
                    //$this->output = "OK";
                    
                    $atomLoader = new Minime_Atom_Loader($this->conf);
                    $atomStorer = new Minime_Atom_Storer($this->conf);
                    
                    $subsLoader = new Minime_User_Subscriptions_Loader($this->conf);
                    $subStorer = new Minime_User_Subscriptions_Storer($this->conf);
                    
                    $postFeed = Atom_Feed::buildFromRawXML($this->phpInput);
                    
                    foreach( $this->subscription->getSubscribers()->getSubscribers() as $sub ) {
                       
                        $feed = $atomLoader->getFeed($sub->getID());
                        foreach($postFeed->getEntries() as $entry) {
                            $feed->addEntry($entry);
                        }
                        $feed->updateUpdated();
                        $atomStorer->storeAtom($sub->getID(), $feed);
                        
                        // let's check if the logo has changed.
                        $usersSubscriptions = $subsLoader->getSubscriptions($sub->getID());
                        $getSubsription = $usersSubscriptions->getSubscriptionByUri($postFeed->getAuthor()->getUri()->getUri());
                        if($getSubsription !== null) {
                            if($postFeed->getLogo() != "" && $getSubsription->getLogo() != $postFeed->getLogo()) {
                                $getSubsription->setLogo($postFeed->getLogo()->getLogo());
                                $usersSubscriptions->addSubscription($getSubsription);
                                $subStorer->storeSubscription($sub->getID(), $usersSubscriptions);
                            }
                        }
                    }
                    
                } else {
                    $this->output = "Signature does not match!";
                }
            }
            // this can be now even 7.1. New Content Notification
            // or 7.3 Content Distribution.
            // http://pubsubhubbub.googlecode.com/svn/trunk/pubsubhubbub-core-0.3.html
            
            //7.3 Content Distribution
            //file_put_contents  ("/tmp/minime-callback.input", print_r(apache_request_headers(), true) . "\n\n" . $this->phpInput . "\n\n" . print_r($_GET, true) . "\n\n" . print_r($_POST, true));
        }
        
    }
    
    /**
     * Method will load subscription from the system.      
     * @return boolean TRUE if subscription is found, false otherwise. 
     */
    public function findAndLoadPubsubhubbubSubscription() {
        $loader = new Minime_Pubsubhubbub_Subscription_Loader($this->conf);
        $this->subscription = $loader->getSubscription($this->getSubID());
        if($this->subscription === null) {
            return false;
        }
        return true;
    }
    
    public function getSubID() {
        if(!isset($this->getParams['subid'])) {
            return null;
        }
        return $this->getParams['subid'];
    }
    
    // TODO FIX THIS METHOD!
    public function getChallenge() {
        
	if(!isset($this->getParams['hub.challenge']) && !isset($this->getParams['hub_challenge'])) {
            return null;
        }
        return isset($this->getParams['hub.challenge']) ? $this->getParams['hub.challenge'] : $this->getParams['hub_challenge'];
    }
}
